package com.edu.nf.util;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Timestamp;
import java.util.Date;


public class ColumnUtil {

    public static Object columnConvert(ResultSet rs,String columnLabel,Class propType) throws SQLException{
        if (!propType.isPrimitive()&&rs.getObject(columnLabel)==null){
            return null;
        }

        Object value = null;

        if (propType.equals(String.class)){
            value = rs.getString(columnLabel);

        } else if(value instanceof String && propType.isEnum()){
            value = Enum.valueOf(propType, rs.getString(columnLabel));

        } else if (propType.equals(Integer.TYPE) || propType.equals(Integer.class)) {
            value = Integer.valueOf(rs.getInt(columnLabel));

        }else if(propType.equals(Boolean.TYPE)||propType.equals(Boolean.class)){
            value = Boolean.valueOf(rs.getBoolean(columnLabel));

        }else if(propType.equals(Long.TYPE)||propType.equals(Long.class)){
            value = Long.valueOf(rs.getLong(columnLabel));

        }else if (propType.equals(Double.TYPE)||propType.equals(Double.class)){
            value = Double.valueOf(rs.getDouble(columnLabel));

        }else if (propType.equals(Float.TYPE)||propType.equals(Float.class)){
            value = Float.valueOf(rs.getFloat(columnLabel));

        }else if (propType.equals(Short.TYPE)||propType.equals(Short.class)){
            value = Short.valueOf(rs.getShort(columnLabel));

        }else if (propType.equals(Byte.TYPE)||propType.equals(Byte.class)){
            value = Byte.valueOf(rs.getByte(columnLabel));

        }else if (propType.equals(SQLXML.class)){
            value = rs.getSQLXML(columnLabel);
        }else{
            value = rs.getObject(columnLabel);

            //处理日期类型
            value = converData(value, propType);
        }
        return value;
    }


    private static Object converData(Object value,Class<?> propType){
        if (value instanceof java.util.Date){
            String type = propType.getName();
            if ("java.sql.Date".equals(type)){
                value = new java.sql.Date(((java.util.Date)value).getTime());
            }else if ("java.sql.time".equals(type)){
                value = new java.sql.Time(((java.util.Date)value).getTime());
            }else if ("java.sql.Timestamp".equals(type)){
                Timestamp ts = (Timestamp)value;
                int nanos = ts.getNanos();
                ((Timestamp)value).setNanos(nanos);
            }
        }
        return value;
    }
}
